<template>
  <md-field>
    <md-input-item v-model="num" type="money" :title="$t('token.transfer_num')"></md-input-item>
    <div style="padding: 20px 40px 0">
      <md-button type="primary" :loading="loading" @click="post" round plain>{{ $t('confirm') }}</md-button>
      <div style="padding-top: 30px; text-align: center">
        <md-button type="link" icon="address-book" @click="log">{{ $t('token.fill_log') }}</md-button>
      </div>
    </div>
  </md-field>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { toast } from '@/style'
import { t } from '@/lang'
import { userInfo } from '@/model/user'
import { amountFormat } from '@/web3';
import { allowance, approve, balance } from '@/web3/contracts/hwd';
import { fill, address } from '@/web3/contracts/lp';

const router = useRouter()
const num = ref(0)
const loading = ref(false)

const post = async() => {
  // 格式化
  const amount = amountFormat(num.value)
  // 开始检测
  if(Number(await balance()) < Number(amount)){
    return toast(t('contracts.hwd.balance'))
  }
  // 判断可用对比价格
  if(Number(await allowance(address)) < Number(amount)) {
    // 授权
    toast(t('contracts.hwd.approve'), 'ring', 0)
    try{
      await approve(address)
    } catch(e) {
      return toast(false)
    }
  }
  loading.value = true
  fill(amount).then(res => {
    toast(t('ok'))
    userInfo()
  }).catch(err => {
    toast(t('token.error'))
  }).finally(() => {
    loading.value = false
  })
}

const log = () => {
  router.push('/token/fill/log')
}

</script>